//
//  HomePageVC.m
//  hnGovernment
//
//  Created by 安仔 on 17/2/24.
//  Copyright © 2017年 安仔. All rights reserved.
//

#import "HomePageVC.h"
#import "SDCycleScrollView.h"
#import "NavHeaderView.h"
#import "HeaderWeather.h"
#import "PublicServerView.h"
#import "TopLineView.h"
#import "HPContenTVCell.h"
#import "CityRecorderController.h"
#import "SelectServiceObj.h"
#import "BannerObj.h"
#import "SserviceByCategoryObj.h"
#import "TLNewsView.h"
#import "DTExhibitionModel.h"
#import "DTWebViewController.h"
#import "MJRefresh.h"
#import "HotCityNewsObj.h"
#import "LocationSelectVC.h"
#import "MoreServiceVC.h"

@interface HomePageVC ()<UITableViewDelegate, UITableViewDataSource, NavHeaderViewDelegate, PublicServerViewDelegate, HPContenTVCellDelegate, TLCycleScrollViewDelegate, TopLineViewDelegate,SDCycleScrollViewDelegate,LocationSelectVCDelegate>
@property (nonatomic, strong) UIScrollView *bottomScroll;
@property (nonatomic, strong) SDCycleScrollView *adScrollView;//广告页
@property (nonatomic, strong) NavHeaderView *navHeaderView;//导航视图
@property (nonatomic, strong) HeaderWeather *headerWeather;//天气数据
@property (nonatomic, strong) PublicServerView *publicServerView;//微平台
@property (nonatomic, strong) UITableView *myTableView;//内容列表
@property (nonatomic, strong) HPContenTVCell *hpCollectionView;//内容视图
@property (nonatomic, strong) TopLineView *topLineView;//今日头条
@property (nonatomic, strong) TLNewsView *scrollNewsView;//今日头条右
@property(nonatomic,strong) NSMutableArray *myDataArray;//全局展台的数据
@property(nonatomic,strong) NSMutableArray *dataArray;//表格展台的数据
@property (nonatomic,strong) NSArray *enhibitionModelArray;// 表格展台模型数据

@end

@implementation HomePageVC
{
    BOOL flag;
    NSMutableArray *bannerUrlArray;
}

//懒加载
- (NSMutableArray *)myDataArray {
    if (!_myDataArray) {
        _myDataArray = [[NSMutableArray alloc] init];
    }
    return _myDataArray;
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.bottomScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, KScreenWidth, KScreenHeight-76*m6Scale)];
    self.bottomScroll.contentSize = CGSizeMake(0, KScreenHeight);
    self.bottomScroll.backgroundColor = [UIColor clearColor];
    self.bottomScroll.showsVerticalScrollIndicator = NO;
    self.bottomScroll.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.bottomScroll];
    self.bottomScroll.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    //创建首页视图
    [self createHomePageView];
    [self createMyTableView];
    [self getAdScrollView];
    [self getScrollNewsView];
    
    self.bottomScroll.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self p_loadDatas];
    }];
    
    // 获取后台数据
    [self p_loadDatas];
    [self.bottomScroll bringSubviewToFront:self.headerWeather];
    
    flag = NO;
    
}

- (void)p_loadDatas {
    [self requestSelectService];
    [self requestSelectServiceByExhibitionCategoryId];
    [self requestBannerContent];
    [self requestHotCityNewsData];
    
    flag = NO;
    
}



//获取轮播
- (void)getAdScrollView{
    NSArray *dataArr = @[@"1", @"2", @"3"];
    self.adScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, KScreenWidth, 286*m6Scale) delegate:self placeholderImage:[UIImage imageNamed:@"暂无数据"]];
    self.adScrollView.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.7];
    self.adScrollView.currentPageDotColor = [UIColor lightGrayColor];
    self.adScrollView.pageDotColor = [UIColor whiteColor];
    self.adScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    self.adScrollView.imageURLStringsGroup = dataArr;
    [self.bottomScroll addSubview:self.adScrollView];
}

//轮播点击事件处理
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    NSLog(@"点击了轮播的第%ld页", index);
    DTWebViewController *webViewController = [[DTWebViewController alloc]init];
    webViewController.webViewUrlString = bannerUrlArray[index];
    webViewController.title = NSLocalString(@"");
    [self.navigationController pushViewController:webViewController animated:YES];
}

//创建滚动头条
- (void)getScrollNewsView {
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    //NSArray *arr1 = @[@"11", @"22"];
    self.scrollNewsView = [[TLNewsView alloc]initWithFrame:CGRectMake(160*m6Scale, 470*m6Scale, self.view.frame.size.width-165*m6Scale,  135*m6Scale)];
    self.scrollNewsView.backgroundColor = [UIColor clearColor];
    //self.scrollNewsView.titlesGroup = self.dataArray;
    self.scrollNewsView.delegate = self;
    [self.bottomScroll addSubview:self.scrollNewsView];
    [self.bottomScroll bringSubviewToFront:self.scrollNewsView];
}

/** 点击图片回调 */
-(void)tlcycleScrollView:(TLNewsView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    //NSLog(@"%ld",index);
    HotCityNewsObj *obj = self.scrollNewsView.titlesGroup[index];
    DTWebViewController *webViewController = [[DTWebViewController alloc]init];
    webViewController.webViewUrlString = obj.url;
    webViewController.title = NSLocalString(@"新闻详情");
    [self.navigationController pushViewController:webViewController animated:YES];
}


//创建首页视图
- (void) createHomePageView {
    
    //导航视图
    self.navHeaderView = [[NavHeaderView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 128*m6Scale)];
    self.navHeaderView.delegate = self;
    [self.view addSubview:self.navHeaderView];
    
    //天气视图
    self.headerWeather = [[HeaderWeather alloc] initWithFrame:CGRectMake(0, 214*m6Scale, KScreenWidth, 72*m6Scale) withSignImg:@"1" withNumLab:@"1" withQualityNum:@"1"];
    [self.bottomScroll addSubview:self.headerWeather];
    
    //微平台
    self.publicServerView = [[PublicServerView alloc] initWithFrame:CGRectMake(0, 286*m6Scale, KScreenWidth, 176*m6Scale) withData:_myDataArray];
    self.publicServerView.delegate = self;
    [self.bottomScroll addSubview:self.publicServerView];
    
    //头条视图
    self.topLineView = [[TopLineView alloc] initWithFrame:CGRectMake(0, 462*m6Scale, KScreenWidth, 144*m6Scale)];
    self.topLineView.delegete = self;
    [self.bottomScroll addSubview:self.topLineView];
}

- (void)createMyTableView {
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 606*m6Scale, KScreenWidth, KScreenHeight - 740*m6Scale - 92*m6Scale) style:UITableViewStyleGrouped];
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.scrollEnabled = NO;
    self.myTableView.userInteractionEnabled = YES;
    [self.bottomScroll addSubview:self.myTableView];
}

#pragma mark - UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.enhibitionModelArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    //NSDictionary *dict = self.dataArray[indexPath.section];
    //NSArray *dataArr = [SserviceByCategoryObj objectArrayWithKeyValuesArray:dict[@"exhibitionService"]];
    //if (dataArr.count <= 0) {
    return 400*m6Scale;
    //} else {
    //NSInteger times1 = dataArr.count/2;
    //NSInteger times2 = dataArr.count%2;
    //CGFloat height = (times1+times2)*150*m6Scale +80*m6Scale;
    //return height;
    //}
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 20*m6Scale;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HPContenTVCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HPCollectionCell"];
    if (!cell) {
        cell = [[HPContenTVCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"HPCollectionCell" Size:CGSizeMake(KScreenWidth, cell.frame.size.height)];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setCellData:self.enhibitionModelArray withSection:indexPath.section];
    return cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

//重写tableview的高度
- (void)setMyTableViewHeight{
    CGFloat resultHeight = 420*m6Scale*self.enhibitionModelArray.count;
    self.myTableView.frame = CGRectMake(0, 606*m6Scale, KScreenWidth, resultHeight);
    [self.myTableView reloadData];
    //重写bottomScroll的滚动范围
    self.bottomScroll.contentSize = CGSizeMake(0, KScreenHeight+resultHeight-630*m6Scale);
}


#pragma mark - 代理方法

/** 点击网格 */
-(void)cellClickCollectionItem:(HPContenTVCell *)cell andItem:(NSInteger)item {
    NSIndexPath *indexpath = [self.myTableView indexPathForCell:cell];

    if (item == 3) {
        MoreServiceVC *vc = [[MoreServiceVC alloc] init];
        DTExhibitionModel *itemModel = self.enhibitionModelArray[indexpath.section];
        vc.collectArray = itemModel.exhibitionService;
        self.navigationController.navigationBar.hidden = NO;
        [self.navigationController pushViewController:vc animated:YES];
        
    } else {
        DTExhibitionModel *itemModel = self.enhibitionModelArray[indexpath.section];
        SelectServiceObj *serviceModel = itemModel.exhibitionService[item];
        DTWebViewController *webViewController = [[DTWebViewController alloc]init];
        webViewController.webViewUrlString = serviceModel.url;
        webViewController.title = serviceModel.serviceName;
        [self.navigationController pushViewController:webViewController animated:YES];
    }
}


/** 点击城市按钮 */
- (void)chooseCity {
    LocationSelectVC *locationVC = [[LocationSelectVC alloc]init];
    [self.navigationController pushViewController:locationVC animated:YES];
    locationVC.delegate = self;
//    [SVProgressHUD showSuccessWithStatus:NSLocalString(@"敬请期待")];
    
}

/** 点击消息按钮 */
- (void)checkHomePageMessage {
    [SVProgressHUD showSuccessWithStatus:NSLocalString(@"敬请期待")];
}

/** 微平台事件，（头条上面） */
- (void)selectPublicServerItem:(NSInteger)index {
    SelectServiceObj *serviceModel = self.myDataArray[index];
    DTWebViewController *webViewController = [[DTWebViewController alloc]init];
    webViewController.webViewUrlString = serviceModel.url;
    webViewController.title = serviceModel.serviceName;
    [self.navigationController pushViewController:webViewController animated:YES]; 
}

/** 点击头条图片进入新闻 */
-(void)TopLineViewClickToNews {
    if (flag) {
        self.navigationController.navigationBar.hidden = NO;
        CityRecorderController *vc = [[CityRecorderController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - 城市选择回调
- (void)selectLocationNameWithString:(NSString *)selectString {

}

#pragma mark 数据请求
//获取全局展台
- (void) requestSelectService {
    
    __weak __typeof(self) weakSelf = self;
    [DDNetWorkManager exhibitionId:@"2" cityId:@"330102" controller:weakSelf success:^(id result, DDcacheType cacheType, DDresultType resultType) {
        //NSLog(@"%@",result[@"data"]);
        int success = [result[@"success"] intValue];
        if (success == 1) {
            self.myDataArray = [SelectServiceObj objectArrayWithKeyValuesArray:result[@"data"]];
            if (![_myDataArray isKindOfClass:[NSArray class]]) {
                _myDataArray = [NSMutableArray array];
            }
            [self.publicServerView setData:_myDataArray];
        }else {
            NSString *errorString = result[@"errorDetail"];
            [SVProgressHUD showErrorWithStatus:errorString];
        }
        [weakSelf.bottomScroll.mj_header endRefreshing];
    } failure:^(NSError *error) {
        [weakSelf.bottomScroll.mj_header endRefreshing];
        [SVProgressHUD showErrorWithStatus:NSLocalString(@"网络错误")];
    }];
}

//根据展台分类查询应用
- (void) requestSelectServiceByExhibitionCategoryId {
    
    __weak __typeof(self) weakSelf = self;
    [DDNetWorkManager exhibitionCategoryId:@"1" cityId:@"330102" controller:weakSelf success:^(id result, DDcacheType cacheType, DDresultType resultType) {
        //NSLog(@"----%@",result);
        int success = [result[@"success"] intValue];
        if (success == 1) {
            self.dataArray = result[@"data"];
            if (![self.dataArray isKindOfClass:[NSArray class]]) {
                self.dataArray = [NSMutableArray array];
            } else {
                self.enhibitionModelArray = [DTExhibitionModel objectArrayWithKeyValuesArray:result[@"data"]];
            }
            [self.myTableView reloadData];
            [self setMyTableViewHeight];
        } else {
            NSString *errorString = result[@"errorDetail"];
            [SVProgressHUD showErrorWithStatus:errorString];
        }
        [weakSelf.bottomScroll.mj_header endRefreshing];
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:NSLocalString(@"网络错误")];
        [weakSelf.bottomScroll.mj_header endRefreshing];
    }];
}

//获取banner数据
- (void)requestBannerContent {
    __weak __typeof(self) weakSelf = self;
    NSMutableArray *adsArray = [[NSMutableArray alloc] init];
    bannerUrlArray = [[NSMutableArray alloc] init];
    [DDNetWorkManager bannerContentWithCityCode:@"330000" controller:weakSelf success:^(id result, DDcacheType cacheType, DDresultType resultType) {
        [DDHudHelper showHudWithResult:result resultSuccess:^{
            NSMutableArray *dataArr = [BannerObj objectArrayWithKeyValuesArray:result[@"data"]];
            [bannerUrlArray removeAllObjects];
            [adsArray removeAllObjects];
            for (BannerObj *obj in dataArr) {
                //根据type取有效obj
                if ([obj.messageType isEqualToString:@"bannerContent"]) {
                    [adsArray addObject:obj.imgUrl];
                    [bannerUrlArray addObject:obj.url];
                }
            }
            //刷新轮播数据
            self.adScrollView.imageURLStringsGroup = adsArray;
            [weakSelf.bottomScroll.mj_header endRefreshing];
        }];
    } failure:^(NSError *error) {
        [weakSelf.bottomScroll.mj_header endRefreshing];
    }];
}


//获取新闻数据
- (void) requestHotCityNewsData {
    __weak __typeof(self) weakSelf = self;
    [DDNetWorkManager hotCityNewsWithController:weakSelf success:^(id result, DDcacheType cacheType, DDresultType resultType) {
        [DDHudHelper showHudWithResult:result resultSuccess:^{
            
            NSArray *array = [HotCityNewsObj objectArrayWithKeyValuesArray:result[@"data"]];
            //NSLog(@"%@",result[@"data"]);
            flag = YES;
            [self getScrollNewsView];
            self.scrollNewsView.titlesGroup = array;
        }];
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:NSLocalString(@"网络错误")];
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
